package com.duing.listnode;

public class KthFromEnd {

    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3, 4, 5};
        ListNode list = ListNode.arrayToListNode(arr);
        //ListNode result = getKthFromEnd(list,2);
        //System.out.println(result.val);
        //
        //LinkedList linkedList = new LinkedList();
        //linkedList.add(1);
        //linkedList.remove(1);

        //ListNode.toCycle(list, 1);
        System.out.println(hasCycle(list));
    }

    public static ListNode getKthFromEnd(ListNode head, int k) {
        int n = 1;
        // 先求出链表总长度
        ListNode tmp = head;
        while (tmp.next != null) {
            n++;
            tmp = tmp.next;
        }
        tmp = head;
        for (int i = 0; i < n - k; i++) {
            tmp = tmp.next;
        }
        //for (int i = 1; i < n - k + 1; i++) {
        //    tmp = tmp.next;
        //}

        return tmp;
    }


    public static boolean hasCycle(ListNode head) {
        // 链表本身不能为空  或者只有一个节点  也是无环的
        if (head == null || head.next == null) {
            return false;
        }

        ListNode slow = head;
        ListNode fast = head;
        while (true) {
            // 没有环时  fast会先走到链表尾部
            if (fast == null || fast.next == null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
            if(slow != null) {
                System.out.print("slow走到" + slow.val);
            }
            if(fast != null) {
                System.out.println(",fast走到" + fast.val);
            }
            if (slow == fast) return true;
        }
    }

}

